<?php
/**
 * Created by PhpStorm.
 * User: mars
 * Date: 2019/1/25
 * Time: 10:32 AM
 */

namespace backend\models;


use api\models\VipItem;
use common\models\GoodRight;
use feehi\components\Feehi;
use yii\helpers\ArrayHelper;
use yii\rbac\Item;

class Goods extends \common\models\Goods
{

    public $i_code;


    public $unitTime;


    public function rules()
    {
        return ArrayHelper::merge(parent::rules(), [
            [['i_code'], 'string'],
        ]);
    }

    public function init()
    {
        $this->unitTime = 3600 * 24 * 30;
        parent::init();
    }

    public function beforeSave($insert)
    {
//        $this->code = $this->description;

        if ( ! UserItem::findOne($this->i_code)) {
            $item            = new   UserItem();
            $item->name      = $this->i_code;
            $item->rule_name = "useGood";
            $item->type      = 2;
            if ($item->save()) {
                $relation            = new GoodRight();
                $relation->item_name = $item->name;
                $relation->save();
                $this->right = $relation->id;
            } else {
                $this->addError('i_code', '权限储存失败');
            }
        } else {
            $relation            = new GoodRight();
            $relation->item_name = $this->i_code;
            $relation->save();
            $this->right = $relation->id;
//            $this->addError('i_code', '权限名重复');
        }

        if ($insert) {
            $this->created_at = $this->updated_at = time();
        } else {
            $this->updated_at = time();
        }

        $this->availability_period = $this->availability_period * $this->unitTime;

        return parent::beforeSave($insert);
    }

    public function afterFind()
    {
        $this->i_code              = GoodRight::findOne($this->right)->item_name;
        $this->availability_period = $this->availability_period / ($this->unitTime);
        parent::afterFind();
    }

}